#include "mqtt-net-communication.h"

MQTTNetCommunication::MQTTNetCommunication(const string &host, uint16_t port)
    : MQTTClient("/mqtt/send/message/topic", "/mqtt/recv/message/topic", 0)
{

	bool ok = this->connect(host, port);
	if(!ok)
	{
		fprintf(stderr, "Fail to mqtt connect\n");
		return;
	}
}

bool MQTTNetCommunication::sendPacket(const vector<uint8_t> &packet)
{
	int ret = this->send(packet.data(), packet.size());
	if(ret < 0)
	{
		fprintf(stderr, "Fail to mqtt sendPacket \n");
		return false;
	}
	return true;
}

bool MQTTNetCommunication::recvPacket(vector<uint8_t> &packet, int timeout)
{
	char buf[1024];
	int  ret = this->recv(buf, sizeof(buf));
	if(ret < 0)
	{
		fprintf(stderr, "Fail to mqtt recv \n");
		return false;
	}
	packet.assign(buf, buf + ret);
	return true;
}

MQTTNetCommunication::~MQTTNetCommunication()
{
	bool ok = this->disconnect();
	if(!ok)
	{
		fprintf(stderr, "Fail to mqtt connect\n");
		return;
	}
}
